package com.yxw.spring6.xmlaop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;


@Component
public class LogAspect {
    //前置通知
    public void beforeMethod(JoinPoint joinPoint){
        //joinPoint.getArgs() 获取通知的目标方法参数
        Object[] args = joinPoint.getArgs();
        String methodName = joinPoint.getSignature().getName();
        System.out.println("Logger1-->前置通知, 方法名称: " + methodName + ", 参数" + Arrays.toString(args));
    }

    //后置通知
    public void afterMethod(JoinPoint joinPoint){
        //JoinPoint 得到通知的一些信息
        //joinPoint.getSignature().getName() 获取增强的目标方法名
        String methodName = joinPoint.getSignature().getName();
        System.out.println("Logger-->后置通知, 方法名称: " + methodName);
    }

    //返回通知
    public void afterReturningMethod(JoinPoint joinPoint,Integer result){

        String methodName = joinPoint.getSignature().getName();
        System.out.println("Logger-->返回通知, 方法名称: " + methodName + ", 返回结果: " + result);
    }


    //异常通知
    public void afterThrowingMethod(JoinPoint joinPoint,Throwable ex){
        //JoinPoint 得到通知的一些信息
        //joinPoint.getSignature().getName() 获取增强的目标方法名
        String methodName = joinPoint.getSignature().getName();
        System.out.println("Logger-->异常通知, 方法名称: " + methodName + ", 异常信息: " + ex);
    }

    //环绕通知
    public Object aroundMethod(ProceedingJoinPoint joinPoint){

        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        String argsStr = Arrays.toString(args);
        Object result = null;
        try {
            System.out.println("环绕通知 目标方法之前,参数:" + argsStr);
            //调用目标方法
             result = joinPoint.proceed();
            System.out.println("环绕通知 目标方法返回之后");

        }catch (Throwable throwable){
            System.out.println("环绕通知 目标方法出现异常 异常信息:" + throwable);
        }finally {
            System.out.println("环绕通知 目标方法执行完后");
        }
        return result;
    }

}
